//
//  MKHTTPRequest.swift
//  Weibo
//
//  Created by mac on 15/12/21.
//  Copyright © 2015年 MK. All rights reserved.
//

import UIKit
import AFNetworking

//定义枚举值 来决定网络请求是用GET还是用POST
enum HTTPMethod: String {
    case POST = "POST"
    case GET = "GET"
}

//网络请求处理层
class MKHTTPRequest: AFHTTPSessionManager {
    //单例对象 - 设置baseURL
    static let sharedHttpRequest: MKHTTPRequest = {
        let shared = MKHTTPRequest()
        let baseNSURL = NSURL(string: "https://api.weibo.com/")
        //设置返回数据的类型
        shared.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return shared
        }()
    
    //网络请求的核心方法的封装 -1.两个必选的参数 2.请求数据的回调 要么成功返回个字典 要么失败返回错误信息
    func requestJSONDict(method: HTTPMethod, URLString: String, parameters: [String : String]?, finished: (isSuccess: [String : AnyObject]?, isError: NSError?) ->()) {
        
        if method == HTTPMethod.POST {
            //POST请求
            POST(URLString, parameters: parameters, progress: { (progress) -> Void in
                print(progress)
                
                }, success: { (_, result) -> Void in
                    //print(result)
                    
                    //请求失败的回调 -需要自定义错误信息
                    let noDataError = NSError(domain: errorDomain, code: -1001, userInfo: [NSLocalizedDescriptionKey : "数据不合法"])
                    print(noDataError)
                    guard let dict = result as? [String : AnyObject] else {
                        finished(isSuccess: nil, isError: noDataError)
                        return
                    }
                    
                    //请求成功的回调
                    finished(isSuccess: dict, isError: nil)
                    
                }) { (__, error) -> Void in
                    print(error)
                    
                    //请求失败的回调
                    finished(isSuccess: nil, isError: error)
            }
            
        }
        
        if method == HTTPMethod.GET {
            //GET请求
            GET(URLString, parameters: parameters, progress: { (progress) -> Void in
                print(progress)
                }, success: { (_, result) -> Void in
                    //print(result)
                    
                    //请求失败的回调
                    let getError = NSError(domain: errorDomain, code: -1002, userInfo: [NSLocalizedDescriptionKey : "网络数据出错"])
                    guard let dict = result as? [String : AnyObject] else {
                        finished(isSuccess: nil, isError: getError)
                        print(getError)
                        return
                    }
                    
                    //请求成功的回调
                    finished(isSuccess: dict, isError: nil)
                    
                }) { (_, error) -> Void in
                    //请求错误的回调
                    finished(isSuccess: nil, isError: error)
                    print(error)
            }
        }
        
    }
    
    
}
